package com.dmall.common.utils;

import com.dmall.common.exception.DmallException;
import com.dmall.modules.admin.entity.AdminUser;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
/**
 * shiro工具类
 * @author Chen 2017/12/7
 */
public class ShiroUtils {
    /**
     * 获取Session
     * @return
     */
    public static Session getSession() {
        return SecurityUtils.getSubject().getSession();
    }

    /**
     * 获取Subject
     * @return
     */
    public static Subject getSubject() {
        return SecurityUtils.getSubject();
    }

    /**
     * 获取当前Session中的用户
     * @return
     */
    public static AdminUser getUserEntity() {
        return (AdminUser) SecurityUtils.getSubject().getPrincipal();
    }

    /**
     * 获取用户ID
     * @return
     */
    public static Long getUserId() {
        return getUserEntity().getId();
    }

    /**
     * 设置Session Key-Value
     * @param key
     * @param value
     */
    public static void setSessionAttribute(Object key, Object value) {
        getSession().setAttribute(key, value);
    }

    /**
     * 获取Session Key-Value
     * @param key
     * @return
     */
    public static Object getSessionAttribute(Object key) {
        return getSession().getAttribute(key);
    }

    /**
     * 判断是否登录
     * @return
     */
    public static boolean isLogin() {
        return SecurityUtils.getSubject().getPrincipal() != null;
    }

    /**
     * 登出
     */
    public static void logout() {
        SecurityUtils.getSubject().logout();
    }

    /**
     * 获取验证码
     * @param key
     * @return
     */
    public static String getKaptcha(String key) {
        Object kaptcha = getSessionAttribute(key);
        if(kaptcha == null){
            throw new DmallException("验证码已失效");
        }
        //获取完以后，就删除key,使验证码失效
        getSession().removeAttribute(key);
        return kaptcha.toString();
    }

}
